import {Table, Space, Tag} from 'antd';
import React, {useState, useEffect} from 'react';
import {getQuestionUserThumbListUsingPost} from "@/api/userController";
import Link from "next/link";
import {doThumbUsingPost} from "@/api/questionController";


export default function FavourQuestionsPage() {
    const [data, setData] = useState<API.QuestionListVO[]>([]);
    const [loading, setLoading] = useState(false);
    const [params, setParams] = useState<API.QuestionListRequest>({
        current: 1,
        pageSize: 10,
    });
    const [total, setTotal] = useState(0);

    const loadData = async () => {
        setLoading(true);
        try {
            const res = await getQuestionUserThumbListUsingPost(params);
            if (res.data) {
                setData(res.data.records);
                setTotal(res.data.total);
            }
        } finally {
            setLoading(false);
        }
    };

    const handleUnThumb = async (questionId: number) => {
        try {
            const request: API.QuestionThumbRequest = { questionId };
            const res = await doThumbUsingPost(request);
            if (res.data) {
                // 成功后移除当前条目
                setData(prev => prev.filter(item => item.id !== questionId));
                // 如果保持分页准确需要重新加载数据
                loadData();
            }
        } catch (error) {
            console.error('取消点赞失败', error);
        }
    };


    useEffect(() => {
        loadData();
    }, [params]);

    // 定义难度颜色映射
    const difficultyColors = {
        简单: {backgroundColor: '#52c41a', color: '#fff'}, // 绿色背景，白色字体
        中等: {backgroundColor: '#fed73b', color: '#fff'}, // 黄色背景，白色字体
        困难: {backgroundColor: '#ff4d4f', color: '#fff'}  // 红色背景，白色字体
    };

    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            render: (_: any, record: API.QuestionListVO) => (
                <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
                    <Link href={`/question/${record.id}`}>{record.title}</Link>
                    {record.isVip ? (
                        <Tag color="gold" style={{fontSize: 10}}>VIP</Tag>
                    ) : (
                        <Tag color="green" style={{fontSize: 10}}>免费</Tag>
                    )}
                </div>
            ),
        },
        {
            title: '难度',
            dataIndex: 'diff',
            key: 'diff',
            render: (_: any, record: API.QuestionListVO) => {
                const diffStyle = difficultyColors[record.diff];
                return <Tag style={{ ...diffStyle, fontSize: 10 }}>{record.diff}</Tag>;
            },
        },
        {
            title: '收藏时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            render: (_: any, record: API.QuestionListVO) => (
                <Space>
                    <a onClick={() => handleUnThumb(record.id)}>取消点赞</a>
                </Space>
            ),
        },
    ];

    return (
        <Table
            columns={columns}
            dataSource={data}
            loading={loading}
            pagination={{
                current: params.current,
                pageSize: params.pageSize,
                total: total,
                showTotal: (total, range) => `共 ${total} 条记录，当前 ${range[0]}-${range[1]} 条`,
                showSizeChanger: true,
                onChange: (page, pageSize) => {
                    setParams(prev => ({...prev, current: page, pageSize}));
                },
            }}
            onChange={(pagination, filters, sorter) => {
                const sortParams = Array.isArray(sorter) ? sorter[0] : sorter;
                setParams(prev => ({
                    ...prev,
                    sortField: sortParams.field?.toString(),
                    sortOrder: sortParams.order?.toString().replace('end', ''),
                }));
            }}
        />
    );
};
